<template>
  <view :class="['home', themeClass]">
    <view class="search">
      <view class="set" @click="returnToTheSuperior">
        <image :src="back" />
      </view>
      <view class="title">
        <text>Pexels</text>
      </view>
      <view class="icon"></view>
    </view>
    <view class="body">
      <ImgList @scrolltolower="scrolltolowerEvent" @refreshEvent="refreshEvent" :imgList="imgList" class="imgList"></ImgList>
      <Loading v-show='loading' class="loadMore"></Loading>
    </view>
  </view>
</template>
<script setup lang="ts">
import { useTheme } from '@/hooks/useTheme'
const { themeClass } = useTheme()
import { onLoad } from '@dcloudio/uni-app'
import back from '@/static/images/back.png'
import { getPexelsImgs } from '@/services/home'
import { ref } from 'vue'

type ImgList = {
  small: string
  src: string
  tag: string
}
const imgList = ref<ImgList[]>([])
const limit = ref(30)
const page = ref(1)
const loading = ref(false)
const getData = async () => {
  loading.value = true
  try {
    const res = await getPexelsImgs({
      limit: limit.value,
      page: page.value
    })
    loading.value = false
    if (res.photos.length == 0) return
    for (let i = 0; i < res.photos.length; i++) {
      imgList.value.push({
        small: res.photos[i].src['large'],
        src: res.photos[i].src['original'],
        tag: res.photos[i].photographer
      })
    }
  } catch (error) {
    loading.value = false
  }
}
const refreshEvent = () => {
  imgList.value = []
  page.value = 1
  getData()
}
const scrolltolowerEvent = () => {
  if (loading.value) return
  page.value++
  getData()
}
const returnToTheSuperior = () => {
  uni.navigateBack()
}
onLoad(() => {
  getData()
})
</script>
<style scoped lang="scss">
.home {
  padding-top: var(--status-bar-height);
  height: 100%;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;

  .search {
    padding: 10rpx;
    display: grid;
    gap: 5px;
    grid-template-columns: 60rpx 1fr 60rpx;

    .set,
    .icon {
      display: flex;
      justify-content: center;
      align-items: center;

      image {
        height: 60rpx;
        width: 60rpx;
      }
    }

    .title {
      display: flex;
      justify-content: center;
      align-items: center;
      padding: 0 20rpx;
      font-weight: bold;
    }
  }

  .body {
    flex: 1;
    position: relative;
    overflow: hidden;
    display: flex;
    flex-direction: column;

    .imgList {
      flex: 1;
    }

    .loadMore {
      left: 50%;
      transform: translateX(-50%);
      bottom: 20rpx;
      position: absolute;
    }
  }
}
</style>
